package br.com.unb.provenance.controller;

import org.hibernate.Session;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.ValidationMessage;
import br.com.unb.provenance.entities.Institution;
import br.com.unb.provenance.entities.Project;

@Resource
@Path("/project")
public class ProjectController {

	private Result result;
	private Session session;
	private Validator validator;
	
	
	public ProjectController(Result result, Session session, Validator validator) {
		this.result = result;
		this.session = session;
		this.validator = validator;
	}



	@Path({"/new", "/edit/{project.id}"})
	@Get	
	public void form(Project project){

	}
	
	@Post
	@Path("/salve")
	public void salve(Project project) {
		doValidation(project);
		validator.onErrorUsePageOf(ProjectController.class).form(project);
		session.save(project);
		for (Institution institution : project.getInstitutions()) {
			institution.setProject(project);
			session.save(institution);
		}
		result.redirectTo(this).form(project);
	}
	
	@Get
	@Path("/search")
	public void search(Project project){
		result.include("listProject", session.createCriteria(Project.class).list());
	}
	
	public void doValidation(Project project){
		if(project.getName() == null || project.getName().isEmpty()){
			validator.add(new ValidationMessage("Field Name is required!", "erro"));
		}		
		if(project.getDescription() == null || project.getDescription().isEmpty()){
			validator.add(new ValidationMessage("Field Description is required!", "erro"));
		}			
	}
}
